package com.macro.mall.utils;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;

public class GaodeCityInfoFetcher {

    // 替换为Web服务类型的Key
    private static final String API_KEY = "b9cfe24bd8bd527bccd270e4a06dbd8e";
    private static final String REVERSE_GEOCODE_URL = "https://restapi.amap.com/v3/geocode/regeo";

    public static String getCityByCoordinates(String longitude, String latitude) {
        String url = String.format("%s?key=%s&location=%s,%s&extensions=base&output=json",
                REVERSE_GEOCODE_URL,
                API_KEY,
                longitude,
                latitude);

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet request = new HttpGet(url);
            // 添加请求头
            request.setHeader("Accept", "application/json");

            CloseableHttpResponse response = httpClient.execute(request);

            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                JSONObject jsonObject = new JSONObject(result);

                if ("1".equals(jsonObject.getString("status"))) {
                    JSONObject regeocode = jsonObject.getJSONObject("regeocode");
                    JSONObject addressComponent = regeocode.getJSONObject("addressComponent");

                    // 处理直辖市情况
                    String city = addressComponent.optString("city", "");
                    if (city.isEmpty()) {
                        city = addressComponent.getString("province");
                    }
                    return city;
                } else {
                    String info = jsonObject.getString("info");
                    String infocode = jsonObject.getString("infocode");
                    System.err.printf("API请求失败: %s (错误码: %s)%n", info, infocode);
                }
            }
        } catch (IOException e) {
            System.err.println("网络请求异常: " + e.getMessage());
        }
        return null;
    }

    public static void main(String[] args) {
        // 测试坐标（阿勒泰地区）
        String longitude = "85.876923";
        String latitude = "47.430427";

        String city = getCityByCoordinates(longitude, latitude);
        if (city != null) {
            System.out.println("获取到的市信息: " + city);
        } else {
            System.out.println("获取市信息失败，请检查：");
            System.out.println("1. API Key是否为Web服务类型");
            System.out.println("2. 坐标是否在中国境内");
            System.out.println("3. 网络连接是否正常");
        }
    }
}

